package com.qiangesoft.pay.app.config;

import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.refund.RefundService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@EnableConfigurationProperties(WxPayProperties.class)
@Configuration
public class WxPayConfig {

    @Autowired
    private WxPayProperties wxPayProperties;

    /**
     * 支付服务
     **/
    @Bean
    public JsapiServiceExtension jsapiServiceExtension() {
        return new JsapiServiceExtension.Builder()
                .config(this.getConfig())
                .signType("RSA")
                .build();
    }

    /**
     * 退款服务
     **/
    @Bean
    public RefundService refundService() {
        return new RefundService.Builder()
                .config(this.getConfig())
                .build();
    }

    /**
     * 回调服务
     **/
    @Bean
    public NotificationParser notificationParser() {
        NotificationConfig config = new RSAAutoCertificateConfig.Builder()
                .merchantId(wxPayProperties.getMchid())
                .privateKeyFromPath(wxPayProperties.getPrivateKeyFromPath())
                .merchantSerialNumber(wxPayProperties.getMerchantSerialNumber())
                .apiV3Key(wxPayProperties.getApiV3Key())
                .build();
        return new NotificationParser(config);
    }

    /**
     * 商户配置
     */
    private Config getConfig() {
        Config config = new RSAAutoCertificateConfig.Builder()
                .merchantId(wxPayProperties.getMchid())
                // 使用 com.wechat.pay.java.core.util 中的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
                .privateKeyFromPath(wxPayProperties.getPrivateKeyFromPath())
                .merchantSerialNumber(wxPayProperties.getMerchantSerialNumber())
                .apiV3Key(wxPayProperties.getApiV3Key())
                .build();
        return config;
    }

}
